package edu.ntu.im.p2ptrade.msg.handle;

import java.security.InvalidKeyException;
import java.security.Signature;

import net.jxta.endpoint.ByteArrayMessageElement;
import net.jxta.endpoint.Message;
import edu.ntu.im.p2ptrade.P2PTrade;
import edu.ntu.im.p2ptrade.RecordManager;
import edu.ntu.im.p2ptrade.Util;
import edu.ntu.im.p2ptrade.msg.AuthenticatedMessageWrapper;
import edu.ntu.im.p2ptrade.msg.PMessage;
import edu.ntu.im.p2ptrade.security.KeyManager;

public class AuthenticatedMessageHandlerWrapper implements PMessageHandle {
	private PMessageHandle handle;
	public AuthenticatedMessageHandlerWrapper(PMessageHandle handle){
		this.handle = handle;
	}

	public void handle(Message msg) throws InvalidKeyException,  Exception {
		System.out.println(msg.toString());
		String peer = msg.getMessageElement(P2PTrade.getInstance().getAppName(), PMessage.PEER).toString();
		ByteArrayMessageElement bame = (ByteArrayMessageElement) msg.getMessageElement(P2PTrade.getInstance().getAppName(), AuthenticatedMessageWrapper.DIGITAL_SIGNATURE);
		byte[] ds = bame.getBytes(true);
		msg.removeMessageElement(bame);
		String content = msg.toString();
		try {
			Signature dsa = Signature.getInstance("SHA1withRSA");
			dsa.initVerify(KeyManager.readCertification(KeyManager.PUBLIC_KEY_FILE)[0].getPublicKey());
			dsa.update(content.getBytes());
			dsa.verify(ds);
			this.handle.handle(msg);
			String logmsg = msg.getMessageElement(P2PTrade.getInstance().getAppName(), AuthenticatedMessageWrapper.LOGMSG).toString();
			System.out.println("logmsg:"+logmsg);
			RecordManager.addRecord(logmsg, msg, peer, P2PTrade.getInstance().getPeerName(), ds);
		} catch (InvalidKeyException e) {
			throw e;
		} catch (Exception e) {
			throw e;
		}
	}

}
